﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Unity;
using PicStore.BLL.Interface;
using PicStore.Common.Email;
using PicStore.Model;
using PicStore.DAL;

namespace PicStore.BLL.Impl
{
    public class RequestService : BaseService, IRequestService
    {
        [Dependency]
        public IUserService UserService { get; set; }

        [Dependency]
        public ICategoryService CategoryService { get; set; }

        public bool SaveDownloadRequest(int userId, DateTime fromDate, DateTime toDate, bool needDownloadPicture, string places, string sexs,
            string department, string phone, string mobile, string project, string leaderName, string comments, out string error)
        {
            bool result = true;
            error = string.Empty;
            var currentUser = UserService.GetUser(userId);
            if (currentUser == null)
            {
                result = false;
            }
            else if (currentUser.Role.Name.ToLower() == RoleEnum.Manager.ToString().ToLower())
            {
                result = false;
            }

            if (result)
            {
                try
                {
                    DownloadRequest request = new DownloadRequest();
                    request.RequestUserId = userId;
                    request.RequestUserName = currentUser.UserName;
                    request.RequestDepartment = department;
                    request.Phone = phone;
                    request.Mobile = mobile;
                    request.Project = project;
                    request.Comments = comments;
                    request.LeaderName = leaderName;
                    request.StartDate = fromDate;
                    request.EndDate = toDate;

                    request.NeedDownloadPicture = needDownloadPicture;
                    request.PlaceValue = places;
                    request.SexValue = sexs;
                    request.Status = (int)RequestStatus.未处理;
                    request.CreateDate = DateTime.Now;

                    if (ConfigurationManager.AppSettings["NeedSendEmail"] == "true")
                    {
                        UEmail email = new UEmail();
                        email.MailTo = ConfigurationManager.AppSettings["AdminEmail"];
                        email.MailSubject = string.Format("Picture Download Request from {0}", request.RequestUserName);

                        StringBuilder sb = new StringBuilder();
                        sb.AppendFormat("(This is the automatic email from picture manangement system, please don't reply it.)<br /><br />");
                        sb.AppendFormat("Request Date：{0}<br />", request.CreateDate);
                        sb.AppendFormat("Request User Name：{0}<br />", request.RequestUserName);
                        sb.AppendFormat("Requester Department：{0}<br />", request.RequestDepartment);
                        sb.AppendFormat("Phone：{0}<br />", request.RequestDepartment);
                        sb.AppendFormat("Mobile：{0}<br />", request.Mobile);
                        sb.AppendFormat("Need Picture from {0} to {1}<br />", request.StartDate, request.EndDate);
                        sb.AppendFormat("Mobile：{0}<br />", request.Mobile);
                        sb.AppendFormat("Project：{0}<br />", request.Project);
                        sb.AppendFormat("Comments：{0}<br />", request.Comments);
                        sb.AppendFormat("Need Download Picture：{0}<br />", request.NeedDownloadPicture);
                        sb.AppendFormat("{0}<br />", CategoryService.GetDescriptionOfItems(request.SexValue, BaseCategoryEnum.Sex));
                        sb.AppendFormat("{0}<br /><br />", CategoryService.GetDescriptionOfItems(request.PlaceValue, BaseCategoryEnum.Place));

                        sb.AppendFormat("-- Eland Picture Management System<br />");
                        email.MailBody = sb.ToString();

                        email.SendDirectly();
                    }

                    dbContext.DownloadRequest.InsertOnSubmit(request);
                    dbContext.SubmitChanges();
                }
                catch (Exception ex)
                {
                    result = false;
                    error = ex.Message;
                    throw;
                }
            }

            return result;
        }

        public List<RequestInfo> GetRequestList(string userName, out int count, out int totalPages, int pageSize, int pageIndex = 1)
        {
            List<RequestInfo> list = new List<RequestInfo>();
            var requests = (from request in dbContext.DownloadRequest
                            join user in dbContext.UserProfile on request.RequestUserId equals user.UserId
                            where user.UserName.Contains(userName) && request.Status != (int)RequestStatus.已删除
                            orderby request.CreateDate descending
                            orderby request.Status ascending
                            select request);

            count = requests.Count();
            totalPages = count / pageSize + (count % pageSize > 0 ? 1 : 0);

            var requestList = requests.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            foreach (var req in requestList)
            {
                list.Add(BuildRequestInfo(req));
            }

            return list;
        }

        public List<RequestInfo> GetApprovedRequestList(string userName, out int count, out int totalPages, int pageSize, int pageIndex = 1)
        {
            List<RequestInfo> list = new List<RequestInfo>();
            var requests = (from request in dbContext.DownloadRequest
                            join user in dbContext.UserProfile on request.RequestUserId equals user.UserId
                            where user.UserName.Contains(userName) && request.Status == (int)RequestStatus.已处理
                            orderby request.CreateDate descending
                            orderby request.Status ascending
                            select request);

            count = requests.Count();
            totalPages = count / pageSize + (count % pageSize > 0 ? 1 : 0);

            var requestList = requests.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            foreach (var req in requestList)
            {
                list.Add(BuildRequestInfo(req));
            }

            return list;
        }

        private RequestInfo BuildRequestInfo(DownloadRequest request)
        {
            var req = new RequestInfo()
            {
                RequestId = request.DownloadRequestId,
                RequestUserId = request.RequestUserId,
                RequestUserName = request.RequestUserName,
                Department = request.RequestDepartment,
                Phone = request.Phone,
                Mobile = request.Mobile,
                Project = request.Project,
                LeaderName = request.LeaderName,
                Comments = request.Comments,
                ApproveUserId = request.RequestUserId,
                NeedDownloadPicture = request.NeedDownloadPicture,
                PlaceValue = request.PlaceValue,
                SexValue = request.SexValue,
                StartDate = request.StartDate,
                EndDate = request.EndDate,
                CreateDate = request.CreateDate,
                Status = request.Status,
                ZipFileUrl = request.ZipFileUrl,
            };

            if (request.LastDownloadTime.HasValue)
            {
                req.LastDownloadTime = request.LastDownloadTime.Value;
            }

            var user = UserService.GetUser(request.RequestUserId);
            req.RequestUserName = user.UserName;

            var approver = UserService.GetUser(request.ApproveUserId);
            if (approver != null)
            {
                req.ApproveUserName = approver.UserName;
            }

            return req;
        }

        public RequestInfo GetRequestById(int requestId)
        {
            var request = (from r in dbContext.DownloadRequest
                           where r.DownloadRequestId == requestId
                           select r).FirstOrDefault();

            RequestInfo info = null;
            if (request != null)
            {
                info = BuildRequestInfo(request);
            }

            return info;
        }

        public void RejectRequestById(int requestId)
        {
            var request = (from r in dbContext.DownloadRequest
                           where r.DownloadRequestId == requestId
                           select r).FirstOrDefault();

            if (request != null)
            {
                request.Status = (int) RequestStatus.已拒绝;
                dbContext.SubmitChanges();
            }
        }

        public void DeleteRequestById(int requestId)
        {
            var request = (from r in dbContext.DownloadRequest
                           where r.DownloadRequestId == requestId
                           select r).FirstOrDefault();

            if (request != null)
            {
                request.Status = (int)RequestStatus.已删除;
                dbContext.SubmitChanges();
            }
        }

        public void ApproveDownloadRequest(int requestId, string zipFileUrl)
        {
            var request = (from r in dbContext.DownloadRequest
                           where r.DownloadRequestId == requestId
                           select r).FirstOrDefault();

            if (request != null)
            {
                request.Status = (int)RequestStatus.已处理;
                request.ZipFileUrl = zipFileUrl;
                request.LastDownloadTime = DateTime.Now;
                dbContext.SubmitChanges();
            }
        }

        public void CleanOldRequest()
        {
            var requests = (from r in dbContext.DownloadRequest
                            where
                                r.Status == (int) RequestStatus.已处理 &&
                                r.LastDownloadTime < DateTime.Now.AddDays(-2).Date
                            select r).ToList();

            if (requests.Count > 0)
            {
                foreach (var request in requests)
                {
                    // 清空原有的url. 防止报错
                    request.ZipFileUrl = string.Empty;
                }
                dbContext.SubmitChanges();
            }
        }
    }
}
